#include "t0022-0.h"
#include "cui.h"
#include "dxtviewer.h"
#include <signal.h>

#define MODNAME             "[DXTV]"
#define DXTVIEWER_UI_CONFIG		"./dxtviewerui.json"
struct dxtviewer_st dv;

int dxtviewer_run(struct t0022_0st *t22)
{
    int retval = -1;
    struct cui_screen_st* cscr = cui_load(DXTVIEWER_UI_CONFIG);
    dv.cscr = cscr;
    t22->p = &dv;
    if (cscr != NULL) {
        struct cui_widget_st *widget = get_widget_byid(&cscr->windowlist, 0);
        cui_screen_push(widget, NULL);
        cui_refresh(widget->cscr, -1);
        while (!IS_T0022_0_QUIT(t22)) {
            cui_draw(cscr);
            cui_eventloop(cscr);
            usleep(200000);
            ERRSYS_FATALPRINT("sleep\n");
        }
        ERRSYS_INFOPRINT("cui unload\n");
        cui_unload(cscr, 1);
    }
    ERRSYS_INFOPRINT("quit\n");


    return retval;
}

int dxtviewer_keyevent(struct cui_widget_st* widget, int key)
{
    ERRSYS_INFOPRINT("[%s]%s KEY=%d dxtviewer_keyevent %p\n", widget->name, __func__, key, dxtviewer_keyevent);
    if (key == KEY_ESC){
        pid_t pid = getpid();
        if (kill(pid, SIGQUIT) == -1) {
            ERRSYS_FATALPRINT("Error sending SIGQUIT\n");
        }
    }
    // ERRSYS_INFOPRINT("[%s]%s KEY=%d end\n", widget->name, __func__, key);
    return CUI_WIDGETEVENT_HANDLED;
}
